﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CollectionUtil.DataStructure.Collections
{
    public class ArrayCollection : Collection
    {
        private Object[] elementData;
        private int size;

        public ArrayCollection()
        {
            elementData = new Object[1];
            size = 0;
        }

        public void Add(object e)
        {
            elementData[size] = e;
            EndSureCapacity(++size);
        }

        public void Remove(object e)
        {
            int index = IndexOf(e);
            if (index == -1) return;
            elementData[index] = elementData[--size];
            elementData[size] = null;
        }

        public bool Contain(object e)
        {
            for (int i = 0; i < size; i++)
            {
                if(elementData[i].Equals(e))
                {
                    return true;
                }
            }
            return false;
        }

        public bool IsEmpty()
        {
            return size == 0;
        }

        public int Size()
        {
            return size;
        }

        public override string ToString()
        {
            string ret = "[";
            for (int i = 0; i < size; i++)
            {
                ret += elementData[i]+",";
            }
            return ret+="]";
        }

        private int IndexOf(Object e)
        {
            for (int i = 0; i < size; i++)
            {
                if (elementData[i].Equals(e))
                    return i;
            }
            return -1;
        }

        private void EndSureCapacity(int c)
        {
            if (c >= elementData.Length)
            {
                Object[] newElementData = new Object[size * 2];
                for (int i = 0; i < size; i++)
                {
                    newElementData[i] = elementData[i];
                }
                elementData = newElementData;
            }
        }

    }
}
